package com.yaolaizaixian.merchant.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import com.xiaomi.market.sdk.UpdateResponse;
import com.xiaomi.market.sdk.UpdateStatus;
import com.xiaomi.market.sdk.XiaomiUpdateAgent;
import com.xiaomi.market.sdk.XiaomiUpdateListener;
import com.yaolaizaixian.merchant.HomeActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.service.DownloadService;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;

import me.drakeet.materialdialog.MaterialDialog;
import okhttp3.Call;

public class UpdateManager {

    private static final String TAG = "UpdateManager";
    private Updata updata;
    private HomeActivity mContext;

    public UpdateManager(HomeActivity context) {
        mContext = context;
    }

    private Handler mGetVersionHandler = new Handler() {
        public void handleMessage(Message msg) {

            String result = (String) msg.obj;

            LogUtil.LogShitou(TAG, result);

            BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);

            if (baseModel.isFlag()) {

                UpdataModel updataModel = GsonUtil.jsonToBean(result, UpdataModel.class);
                updata = (Updata) updataModel.getData();
                if (null != updata)
                {
                    if (isUpdate(updata.getVersion())) {

                        //不强制更新
                        if (updata.getUpdate().equals("0")) {

                            updata();
                            //Miupdata(false);

                        }
                        //强制更新
                        else if (updata.getUpdate().equals("1")) {

                            qiangzhiupdata();
                            //Miupdata(true);

                        }

                    } else {

                    }
                } else {

                    return;

                }
            } else {

                return;
            }
        }

        ;
    };

    /*
     * 检测软件是否需要更新
     */
    public void checkUpdate(Context context) {

        final String url = BaseInfo.URL + "versionController/versionInfo.do";
        HashMap<String, String> sortedParams = new HashMap<String, String>();
        //版本号
        sortedParams.put("version",String.valueOf(MyUtils.getVersion(context)));
        //apptype Android
        sortedParams.put("appType","2");
        //权益结合
        OkHttpUtils
                .post()
                .url(url)
                .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, context))
                .build()
                .execute(new MyStringCallback());
    }

    class MyStringCallback extends StringCallback {

        @Override
        public void onError(Call call, Exception e, int id) {

        }
        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mGetVersionHandler.sendMessage(message);
        }

    }


    private static PackageInfo getPackageInfo(Context context) {

        PackageInfo pi = null;

        try {

            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            return pi;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    /*
     * 与本地版本比较判断是否需要更新
     */
    protected boolean isUpdate(String servercode) {

        Double serverVersion = Double.parseDouble(servercode);

        int localVersion = 1;

        localVersion = MyUtils.getVersion(mContext);

        if (serverVersion > localVersion) {

            return true;

        } else {

            return false;
        }
    }

    //强制更新
    private void qiangzhiupdata() {

       final MaterialDialog mMaterialDialog = new MaterialDialog(mContext);
        mMaterialDialog.setMessage("有新版本需要更新");
        mMaterialDialog.setPositiveButton("更新", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //XiaomiUpdateAgent.arrange();
                Intent intent = new Intent(mContext, DownloadService.class);
                Log.e(TAG, updata.getUrl());
                intent.putExtra("url", updata.getUrl());
                mContext.startService(intent);
                mMaterialDialog.dismiss();
            }
        });

        mMaterialDialog.show();

    }

    //非强制更新
    private void updata() {

       final MaterialDialog mMaterialDialog = new MaterialDialog(mContext);
        mMaterialDialog.setMessage("有新版本需要更新");
        mMaterialDialog.setPositiveButton("更新", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               // XiaomiUpdateAgent.arrange();
                // 显示下载对话框
                Intent intent = new Intent(mContext, DownloadService.class);
                Log.e(TAG, updata.getUrl());
                intent.putExtra("url", updata.getUrl());
                mContext.startService(intent);
                mMaterialDialog.dismiss();
            }
        });

        mMaterialDialog.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mMaterialDialog.dismiss();
            }
        });

        mMaterialDialog.show();

    }

 /*  private void showWifi() {

        final MaterialDialog mMaterialDialog01 = new MaterialDialog(mContext);
        mMaterialDialog01.setMessage("现在非WIFI环境，是否继续下载？");
        mMaterialDialog01.setPositiveButton("是", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 显示下载对话框
                Intent intent = new Intent(mContext, DownloadService.class);
                Log.e(TAG,updata.getUrl());
                intent.putExtra("url", updata.getUrl());
                mContext.startService(intent);
                mMaterialDialog01.dismiss();

            }
        });
        mMaterialDialog01.setNegativeButton("否", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mMaterialDialog01.dismiss();
                //点击关闭，退出整个应用
                mContext.finish();

            }
        });

        mMaterialDialog01.show();

    }*/

    //小米增量更新   传入是否强制
    public void Miupdata(final boolean isQiangzhi)
    {

        XiaomiUpdateAgent.setUpdateAutoPopup(false);
        XiaomiUpdateAgent.setUpdateListener(new XiaomiUpdateListener() {
            @Override
            public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
                switch (updateStatus) {

                    case UpdateStatus.STATUS_UPDATE:
                        // 有更新， UpdateResponse为本次更新的详细信息
                        // 其中包含更新信息，下载地址，MD5校验信息等，可自行处理下载安装
                        // 如果希望 SDK继续接管下载安装事宜，可调用
                        //  XiaomiUpdateAgent.arrange()
                        if (isQiangzhi) {

                             qiangzhiupdata();

                             Log.e(TAG, "强制更新");

                        } else {

                            updata();
                            Log.e(TAG, "不强制更新");
                        }

                        break;
                    case UpdateStatus.STATUS_NO_UPDATE:
                        // 无更新， UpdateResponse为null

                        Log.e(TAG,"无更新");

                        break;
                    case UpdateStatus.STATUS_NO_WIFI:
                        // 设置了只在WiFi下更新，且WiFi不可用时， UpdateResponse为null
                        break;
                    case UpdateStatus.STATUS_NO_NET:
                        // 没有网络， UpdateResponse为null
                        break;
                    case UpdateStatus.STATUS_FAILED:
                        // 检查更新与服务器通讯失败，可稍后再试， UpdateResponse为null
                        break;
                    case UpdateStatus.STATUS_LOCAL_APP_FAILED:
                        // 检查更新获取本地安装应用信息失败， UpdateResponse为null
                        break;
                    default:
                        break;
                }
            }
        });

       XiaomiUpdateAgent.update(mContext);

    }

}
